package com.shuoyue.ycgk.net;


import com.google.gson.GsonBuilder;
import com.shuoyue.ycgk.Constant;
import com.shuoyue.ycgk.appcatch.MemeryCatch;
import com.shuoyue.ycgk.net.api.APIService;
import com.shuoyue.ycgk.net.gsondefaultadapter.DoubleDefaultAdapter;
import com.shuoyue.ycgk.net.gsondefaultadapter.FloatDefaultAdapter;
import com.shuoyue.ycgk.net.gsondefaultadapter.IntegerDefaultAdapter;
import com.shuoyue.ycgk.net.gsondefaultadapter.LongDefaultAdapter;
import com.shuoyue.ycgk.net.gsondefaultadapter.StringNullAdapter;

import org.apache.http.conn.ssl.AllowAllHostnameVerifier;

import java.util.Arrays;
import java.util.concurrent.TimeUnit;

import okhttp3.ConnectionSpec;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.TlsVersion;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;


public class RetrofitClient {
    private static volatile RetrofitClient instance;

    private APIService accountApiService;

    private RetrofitClient() {
    }

    public static RetrofitClient getInstance() {
        if (instance == null) {
            synchronized (RetrofitClient.class) {
                if (instance == null) {
                    instance = new RetrofitClient();
                }
            }
        }
        return instance;
    }


    public APIService getApi() {
        if (accountApiService == null) {
            accountApiService = getRetrofitClient().create(APIService.class);
        }
        return accountApiService;
    }


//<editor-folder desc="基础配置">

    /**
     * 设置Header
     *
     * @return
     */
    private Interceptor getHeaderInterceptor() {
        return chain -> {
            Request original = chain.request();
            Request.Builder requestBuilder = original.newBuilder()
                    //添加Token
                    .header("token", MemeryCatch.token)
//                    .header("notes-questionType", "multipart/form-data")
                    ;
            Request request = requestBuilder.build();
            return chain.proceed(request);
        };

    }


    private Retrofit getUploadFileRetrofitClient() {
        OkHttpClient okHttpClient;
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.addInterceptor(getHeaderInterceptor());
        builder.addInterceptor(getLogInterceptor());
        //超时时间
        builder.connectTimeout(3, TimeUnit.SECONDS);//15S连接超时
        builder.readTimeout(10, TimeUnit.SECONDS);//20s读取超时
        builder.writeTimeout(10, TimeUnit.SECONDS);//20s写入超时

        builder.hostnameVerifier(new AllowAllHostnameVerifier());

        //错误重连
        builder.retryOnConnectionFailure(true);
        ConnectionSpec spec = new ConnectionSpec.Builder(ConnectionSpec.COMPATIBLE_TLS)
                .tlsVersions(TlsVersion.TLS_1_2, TlsVersion.TLS_1_1, TlsVersion.TLS_1_0)
                .allEnabledCipherSuites()
                .build();//解决在Android5.0版本以下https无法访问
        ConnectionSpec spec1 = new ConnectionSpec.Builder(ConnectionSpec.CLEARTEXT).build();//兼容http接口
        builder.connectionSpecs(Arrays.asList(spec, spec1));
        okHttpClient = builder.build();

        return new Retrofit.Builder()
                .client(okHttpClient)
                .baseUrl(Constant.HOST_INTERFACE)
                .addConverterFactory(GsonConverterFactory.create(new GsonBuilder()
                        .setDateFormat("yyyy-MM-dd HH:mm:ss")
                        .registerTypeAdapter(Integer.class, new IntegerDefaultAdapter())
                        .registerTypeAdapter(int.class, new IntegerDefaultAdapter())
                        .registerTypeAdapter(Double.class, new DoubleDefaultAdapter())
                        .registerTypeAdapter(double.class, new DoubleDefaultAdapter())
                        .registerTypeAdapter(Long.class, new LongDefaultAdapter())
                        .registerTypeAdapter(long.class, new LongDefaultAdapter())
                        .registerTypeAdapter(Float.class, new FloatDefaultAdapter())
                        .registerTypeAdapter(float.class, new FloatDefaultAdapter())
                        .registerTypeAdapter(String.class, new StringNullAdapter())
                        .create()))
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();
    }

    private Retrofit getRetrofitClient() {
        return getRetrofitClient(false);
    }

    private Retrofit getRetrofitClient(boolean isDownload) {
        ConnectionSpec spec = new ConnectionSpec.Builder(ConnectionSpec.COMPATIBLE_TLS)
                .tlsVersions(TlsVersion.TLS_1_2, TlsVersion.TLS_1_1, TlsVersion.TLS_1_0)
                .allEnabledCipherSuites()
                .build();//解决在Android5.0版本以下https无法访问
        ConnectionSpec spec1 = new ConnectionSpec.Builder(ConnectionSpec.CLEARTEXT).build();//兼容http接口
        OkHttpClient client = new OkHttpClient().newBuilder()
                //设置Header
                .addInterceptor(getHeaderInterceptor())
                //设置Log拦截器
                .addInterceptor(getLogInterceptor())
                .callTimeout(25, TimeUnit.SECONDS)
                .connectTimeout(25, TimeUnit.SECONDS)
                .writeTimeout(25, TimeUnit.SECONDS)
                .readTimeout(25, TimeUnit.SECONDS)
                .hostnameVerifier(new AllowAllHostnameVerifier())
                .connectionSpecs(Arrays.asList(spec, spec1))
                .build();
        return new Retrofit.Builder()
                .client(client)
                .baseUrl(Constant.HOST_INTERFACE)
                .addConverterFactory(GsonConverterFactory.create(new GsonBuilder()
                        .setDateFormat("yyyy-MM-dd HH:mm:ss")
                        .registerTypeAdapter(Integer.class, new IntegerDefaultAdapter())
                        .registerTypeAdapter(int.class, new IntegerDefaultAdapter())
                        .registerTypeAdapter(Double.class, new DoubleDefaultAdapter())
                        .registerTypeAdapter(double.class, new DoubleDefaultAdapter())
                        .registerTypeAdapter(Long.class, new LongDefaultAdapter())
                        .registerTypeAdapter(long.class, new LongDefaultAdapter())
                        .registerTypeAdapter(Float.class, new FloatDefaultAdapter())
                        .registerTypeAdapter(float.class, new FloatDefaultAdapter())
                        .registerTypeAdapter(String.class, new StringNullAdapter())
                        .create()))
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();
    }
    //</editor-folder desc="基础配置">

    /**
     * 获取日志拦截器
     *
     * @return
     */
    private Interceptor getLogInterceptor() {

        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        //显示日志
        interceptor.level(HttpLoggingInterceptor.Level.BODY);
        return interceptor;
    }


}
